﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FD.Tools.CopyAssist
{
    /**
     * Created By: Jackie Lee(天宇遊龍)
     * CreatedOn: 2018-02-06
     */
    public static class Extensions
    {
        /// <summary>
        /// 实体转Json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// Json转实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T FromJson<T>(this string str)
        {
            return JsonConvert.DeserializeObject<T>(str);
        }

        /// <summary>
        /// 是否空字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str) || str.Trim().Length == 0;
        }

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool IsDirExists(this string path)
        {
            return Directory.Exists(path);
        }

        /// <summary>
        /// 分隔
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string[] SplitString(this string str)
        {
            return str.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
        }

        /// <summary>
        /// 是否选择是
        /// </summary>
        /// <param name="choose"></param>
        /// <returns></returns>
        public static bool IsChooseOK(this string choose, bool bDefaultTrue = true)
        {
            return (bDefaultTrue && choose.IsNullOrEmpty()) ||
                choose.Equals("y", StringComparison.OrdinalIgnoreCase) ||
                choose.Equals("yes", StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 忽略大小写
        /// </summary>
        /// <param name="collect"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IgnoreContains(this IEnumerable<string> collect, string str)
        {
            return collect.Contains(str, new IgnoreCaseStringComparer());
        }
    }

    internal class IgnoreCaseStringComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            return x.Equals(y, StringComparison.OrdinalIgnoreCase);
        }

        public int GetHashCode(string obj)
        {
            return obj.GetHashCode();
        }
    }
}
